<template>
    <header>
        <div class="search-return" @click="goBack">
            <i class="iconfont icon-fanhui"></i>
        </div>
        <div class="search-main">
            <i class="iconfont icon-fangdajing1"></i>
            <form action="" onsubmit="return false" @keyup.enter="goSearchList">
                <input type="search" placeholder="搜索你喜欢的产品" v-model="searchVal">
            </form>
            
        </div>
        <div class="search-btn" @click="goSearchList">搜索</div>
    </header>
</template>
<script>
export default({
    name:"Header",
    data(){
        return {
            searchVal:this.$route.query.key || '',
            searchArr:[],
        }
    },
    //解决搜索后跳转页面并且在header部分显示搜索的关键字
    created(){
        // console.log(this.$route.query);
    },
    methods:{
        goBack(){
            this.$router.push('/home');
        },
        goSearchList(){
            //如果搜索的关键字没有，是空白，就直接return
            if(!this.searchVal)  return;

            //判断之间有没有本地存储
            if( !localStorage.getItem('searchList')){
                //没有
                localStorage.getItem('searchList','[]');
            }else{
                //如果有
                this.searchArr = JSON.parse(localStorage.getItem('searchList'));
            }

            //增加数据
            this.searchArr.unshift(this.searchVal);
            //ES6去重
            let newArr  = new Set(this.searchArr);

            //给本地存储赋值
            localStorage.setItem('searchList',JSON.stringify(Array.from(newArr)));
            console.log(this.searchVal);


            //路径如果没有变化，不跳转页面
            if(this.searchVal === this.$route.query.key) return;
            //跳转页面的   当前跳转当前会报错
            this.$router.push({
                name:'list',
                query:{
                    key:this.searchVal
                }
            });
        }
    }
})
</script>
<style scoped>
header{
    display: flex;
    justify-content: space-between;
    align-items: center;
    width: 100%;
    height: 2.75rem;
    background-color: green;
    color: #fff;

}
.search-return{
    padding: 0 0.625rem;
}

.search-reurns i{
    font-size: 1.75rem;
}
.search-main{
    width: 16.25rem;
    height: 1.875rem;
    display: flex;
    align-items: center;
    background-color: #fff;
    color: #666;
    border-radius: 0.75rem;
}
.search-main form{
    display: flex;
    justify-content: center;
    align-items: center;
    width: 100%;
}
.search-main form input{
    width: 100%;
}
.search-main i{
    padding: 0 0.625rem;
    color: black;
}
.search-btn{
    padding: 0 0.625rem;
    font-size: 1rem;
}
</style>